//
//  FavoriteCache.swift
//  hello
//
//  Created by 赵康 on 2025/4/15.
//

import Vapor
import Redis

struct FavoriteCache {
  let cache: Cache
  let logger: Logger
  
  init(req: Request) {
    self.cache = Cache(logger: req.logger)
    self.logger = req.logger
  }
  
  // 缓存收藏列表
  func cacheFavorites(_ favorites: [AlbumResponse], forUserID userID: UUID, on req: Request) async throws {
    let key = CacheConfig.KeyBuilder.favorites(userID: userID)
    logger.info("开始缓存用户收藏列表: userID=\(userID), 专辑数量=\(favorites.count), 缓存键=\(key)")
    try await cache.set(
      favorites,
      forKey: key,
      duration: CacheConfig.Duration.medium,
      type: .search,
      on: req.redis
    )
    logger.info("已缓存用户 \(userID) 的收藏列表: 完成")
  }
  
  // 获取缓存的收藏列表
  func getCachedFavorites(forUserID userID: UUID, on req: Request) async throws -> [AlbumResponse]? {
    let key = CacheConfig.KeyBuilder.favorites(userID: userID)
    logger.info("尝试获取缓存的收藏列表: userID=\(userID), 缓存键=\(key)")
    let result = try await cache.get(forKey: key, as: [AlbumResponse].self, from: req.redis)
    if let favorites = result {
      logger.info("命中缓存: 用户 \(userID) 的收藏列表, 包含 \(favorites.count) 个专辑")
    } else {
      logger.info("缓存未命中: 用户 \(userID) 的收藏列表")
    }
    return result
  }
  
  // 缓存收藏夹列表
  func cacheFolders(_ folders: [FolderResponse], forUserID userID: UUID, on req: Request) async throws {
    let key = CacheConfig.KeyBuilder.folders(userID: userID)
    logger.info("开始缓存用户收藏夹列表: userID=\(userID), 收藏夹数量=\(folders.count), 缓存键=\(key)")
    try await cache.set(
      folders,
      forKey: key,
      duration: CacheConfig.Duration.medium,
      type: .search,
      on: req.redis
    )
    logger.info("已缓存用户 \(userID) 的收藏夹列表: 完成")
  }
  
  // 获取缓存的收藏夹列表
  func getCachedFolders(forUserID userID: UUID, on req: Request) async throws -> [FolderResponse]? {
    let key = CacheConfig.KeyBuilder.folders(userID: userID)
    logger.info("尝试获取缓存的收藏夹列表: userID=\(userID), 缓存键=\(key)")
    let result = try await cache.get(forKey: key, as: [FolderResponse].self, from: req.redis)
    if let folders = result {
      logger.info("命中缓存: 用户 \(userID) 的收藏夹列表, 包含 \(folders.count) 个收藏夹")
    } else {
      logger.info("缓存未命中: 用户 \(userID) 的收藏夹列表")
    }
    return result
  }
  
  // 缓存收藏夹内的专辑
  func cacheAlbumsInFolder(_ albums: [AlbumResponse], forUserID userID: UUID, folderID: UUID, sortOrder: FavoritesSortOrder? = nil, on req: Request) async throws {
    let key = CacheConfig.KeyBuilder.albumsInFolder(userID: userID, folderID: folderID, sortOrder: sortOrder)
    logger.info("开始缓存收藏夹内专辑: userID=\(userID), folderID=\(folderID), 排序方式=\(sortOrder?.rawValue ?? "默认"), 专辑数量=\(albums.count), 缓存键=\(key)")
    try await cache.set(
      albums,
      forKey: key,
      duration: CacheConfig.Duration.medium,
      type: .search,
      on: req.redis
    )
    logger.info("已缓存用户 \(userID) 的收藏夹 \(folderID) 中的专辑: 完成")
  }
  
  // 获取缓存的收藏夹内的专辑
  func getCachedAlbumsInFolder(forUserID userID: UUID, folderID: UUID, sortOrder: FavoritesSortOrder? = nil, on req: Request) async throws -> [AlbumResponse]? {
    let key = CacheConfig.KeyBuilder.albumsInFolder(userID: userID, folderID: folderID, sortOrder: sortOrder)
    logger.info("尝试获取缓存的收藏夹内专辑: userID=\(userID), folderID=\(folderID), 排序方式=\(sortOrder?.rawValue ?? "默认"), 缓存键=\(key)")
    let result = try await cache.get(forKey: key, as: [AlbumResponse].self, from: req.redis)
    if let albums = result {
      logger.info("命中缓存: 用户 \(userID) 的收藏夹 \(folderID) 中的专辑, 包含 \(albums.count) 个专辑")
    } else {
      logger.info("缓存未命中: 用户 \(userID) 的收藏夹 \(folderID) 中的专辑")
    }
    return result
  }
  
  // 清除用户的收藏相关缓存
  func clearUserFavoriteCache(userID: UUID, on req: Request) async throws {
    logger.info("开始清除用户 \(userID) 的收藏相关缓存")
    
    // 清除收藏列表缓存
    let favoritesKey = CacheConfig.KeyBuilder.favorites(userID: userID)
    try await cache.delete(forKey: favoritesKey, on: req.redis)
    logger.info("已清除收藏列表缓存: key=\(favoritesKey)")
    
    // 清除收藏夹列表缓存
    let foldersKey = CacheConfig.KeyBuilder.folders(userID: userID)
    try await cache.delete(forKey: foldersKey, on: req.redis)
    logger.info("已清除收藏夹列表缓存: key=\(foldersKey)")
    
    // 清除所有收藏夹内专辑缓存，使用模式匹配删除
    let pattern = "App:version:album:folder:user\(userID)*"
    try await cache.batchDelete(forPattern: pattern, on: req.redis)
    logger.info("已清除收藏夹内专辑缓存: pattern=\(pattern)")
    
    logger.info("用户 \(userID) 的收藏相关缓存清除完成")
  }
}

